package com.fand.manager.service.impl;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import javax.annotation.Resource;

import cn.hutool.core.date.DateUtil;
import com.fand.stater.constant.EventCodeEnum;
import com.fand.stater.constant.FandIndexConstant;
import com.fand.manager.model.es.SysUserLoginReturnDTO;
import com.fand.manager.model.mongo.SysUserDayRecord;
import com.fand.manager.service.ISysUserESIndexRecordService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedCardinality;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

/**
 * Author: zhangjiabin
 * Email: javaboyok@163.com
 * CreateDate: 2021/6/22
 * Version: 1.0
 */
@Slf4j
@Service
public class SysUserESIndexRecordServiceImpl implements ISysUserESIndexRecordService {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private MongoTemplate       mongoTemplate;

    @SneakyThrows
    @Override
    public void recode2Mongo() {
        SearchRequest searchRequest = new SearchRequest(FandIndexConstant.FAND_USER_COLLECTION_RECORD);
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        searchSourceBuilder.size(0);
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("count_user").field("userCode.keyword")
                .subAggregation(AggregationBuilders.cardinality("dis_user").field("userCode.keyword"))
                .size(Integer.MAX_VALUE);
        searchSourceBuilder.aggregation(aggregationBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        ParsedStringTerms parsedStringTerms = searchResponse.getAggregations().get("count_user");


        AtomicLong sumLong = new AtomicLong();
        AtomicLong countLong = new AtomicLong();
        parsedStringTerms.getBuckets().stream().forEach(subParsedStringTerms -> {
            sumLong.addAndGet(((Terms.Bucket) subParsedStringTerms).getDocCount());
            Aggregations aggregations = ((Terms.Bucket) subParsedStringTerms).getAggregations();
            aggregations.asList().stream().forEach(aggregation -> {
                countLong.addAndGet(((ParsedCardinality) aggregation).getValue());
            });
        });
        log.info("今日登录人次为:{},人数为:{}", sumLong.get(), countLong.get());
        SysUserDayRecord sysUserDayRecord = SysUserDayRecord.builder()
                .dateTime(DateUtil.formatDateTime(new Date()))
                .loginCount(countLong.get())
                .loginSum(sumLong.get())
                .loginDate(DateUtil.formatDate(new Date()))
                .time(System.currentTimeMillis())
                .build();
        mongoTemplate.save(sysUserDayRecord);
        log.info("统计今天登录人次完成");
    }

    @SneakyThrows
    @Override
    public SysUserLoginReturnDTO realTimeData() {
        SearchRequest searchRequest = new SearchRequest(FandIndexConstant.FAND_USER_COLLECTION_RECORD);
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        searchSourceBuilder.query(QueryBuilders.termQuery("eventCode.keyword", EventCodeEnum.INDEX.getCode()));
        searchSourceBuilder.size(0);
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("count_user").field("userId")
                .size(Integer.MAX_VALUE);
        searchSourceBuilder.aggregation(aggregationBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        ParsedLongTerms parsedLongTerms = searchResponse.getAggregations().get("count_user");

        AtomicLong sumLong = new AtomicLong();
        parsedLongTerms.getBuckets().stream().forEach(subParsedLongTerms -> sumLong.addAndGet(((Terms.Bucket) subParsedLongTerms).getDocCount())
        );
        log.info("今日登录人次为:{},人数为:{}", sumLong.get());

        SysUserLoginReturnDTO sysUserLoginReturnDTO = SysUserLoginReturnDTO.builder()
                .dateTime(DateUtil.formatDateTime(new Date()))
                .loginSum(sumLong.get())
                .time(System.currentTimeMillis())
                .build();
        return sysUserLoginReturnDTO;
    }
}
